﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using INTEXReportSrv;
using Microsoft.Live;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>

    public partial class SDTDBSYN : DocumentBase, IRefreshTokenHandler
    {
        #region====================Properties=======================
        string company = "";
        string dbtype = "SDF";
        ArrayList scopes = new ArrayList();
        string[] scope;// =( "wl.basic wl.photos wl.skydrive wl.offline_access wl.signin wl.skydrive_update");
        private const string ClientID = "00000000440E0BB5";
        private LiveAuthForm authForm;
        private LiveAuthClient liveAuthClient;
        public LiveConnectClient LiveClient;
        private RefreshTokenInfo refreshTokenInfo;
        private LiveAuthClient AuthClient
        {
            get
            {
                if (this.liveAuthClient == null)
                {
                    this.AuthClient = new LiveAuthClient(ClientID, this);
                }

                return this.liveAuthClient;
            }

            set
            {
                if (this.liveAuthClient != null)
                {
                    this.liveAuthClient.PropertyChanged -= this.liveAuthClient_PropertyChanged;
                }

                this.liveAuthClient = value;
                if (this.liveAuthClient != null)
                {
                    this.liveAuthClient.PropertyChanged += this.liveAuthClient_PropertyChanged;
                }

                this.LiveClient = null;
            }
        }
        private void liveAuthClient_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Session")
            {
                this.UpdateUIElements();
            }
        }
        private void UpdateUIElements()
        {
            LiveConnectSession session = this.AuthSession;
            bool isSignedIn = session != null;
            this.txtMANDANT.Text = company;
            /*this.signOutButton.Enabled = isSignedIn;
            this.connectGroupBox.Enabled = isSignedIn;
            this.currentScopeTextBox.Text = isSignedIn ? string.Join(" ", session.Scopes) : string.Empty;
            if (!isSignedIn)
            {
                this.meNameLabel.Text = string.Empty;
                this.mePictureBox.Image = null;
            }*/
        }

        private LiveConnectSession AuthSession
        {
            get
            {
                return this.AuthClient.Session;
            }
        } 
        private CancellationTokenSource cts;
        DataSet SetMap = null;
        bool success = true;
        bool IsRunning = false;
        string failreason = "";
        string root = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\");
        public OracleConnection OracleDB;
        public SqlConnection SqlServerDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        INTEXDBC INTEXDBC;
        bool isrun = true;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public DataSet SetExt;
        string Today
        {
            get
            {
                return System.DateTime.Now.Year.ToString()
                    + m_Data.Right("00" + System.DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + System.DateTime.Now.Day.ToString(), 2);
            }
        }
        BATCHVKVV m_wintex;
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }
        SDTDBSYNData m_Data, m_DataX;
        private DataRow dwUI;
        ExcelX.ExcelLib.ExcelAgent m_exAgent;

        string UserID = "";
        string ART = "";
    
 
        public SDTDBSYN()
        {
            InitializeComponent();
            this.Name = "SDTDBSYN";
            this.Title = "准备数据";
        }
        #endregion
        //BackgroundWorker bgWorker; 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
             try
            {
                scopes.Add("wl.basic");
                scopes.Add("wl.skydrive");
                scope = new string[scopes.Count];
                scopes.CopyTo(scope);
            }
            catch (LiveAuthException)
            {
                // TODO: Display the exception
            }
        }
        private  void SkyDriveLogIn()
        {
            if (this.authForm == null)
            {
                string startUrl = this.AuthClient.GetLoginUrl(scope);
                string endUrl = "https://login.live.com/oauth20_desktop.srf";
                this.authForm = new LiveAuthForm(
                    startUrl,
                    endUrl,
                    this.OnAuthCompleted);
                this.authForm.FormClosed += AuthForm_FormClosed;
                this.authForm.ShowDialog(null);
            }
        }
        void AuthForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.CleanupAuthForm();
        }

        private void CleanupAuthForm()
        {
            if (this.authForm != null)
            {
                this.authForm.Dispose();
                this.authForm = null;
            }
        }

        private async void OnAuthCompleted(AuthResult result)
        {
            this.CleanupAuthForm();
            if (result.AuthorizeCode != null)
            {
                try
                {
                    LiveConnectSession session = await this.AuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode);
                    this.LiveClient = new LiveConnectClient(session);
                    LiveOperationResult meRs = await this.LiveClient.GetAsync("me");
                    dynamic meData = meRs.Result;
                                        LiveDownloadOperationResult meImgResult = await this.LiveClient.DownloadAsync("me/picture");
                    m_Data.LiveClient = LiveClient;
                }
                catch (LiveAuthException aex)
                {
                    Tracer.Error(aex.StackTrace, aex.Message);
                }
                catch (LiveConnectException cex)
                {
                    Tracer.Error(cex.StackTrace, cex.Message);
                }
            }
            else
            {
                Tracer.Error(result.ErrorCode, result.ErrorDescription);
            }
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    company = (string)dicParamater["Company"];
                    m_Data = new SDTDBSYNData(OracleDB, proxy);
                    INTEXDBC = new INTEXDBC(OracleDB, proxy);
                    #region============TESTINGDATA================ 
                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"];
                    #endregion
                  
                    SetExt = new DataSet();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {

            /*if (m_Data.LiveClient == null)
                m_Data.LiveClient = LiveClient;*/
            using (new LongOperation(this, "正在生成报表，请耐心等待"))
            {
                dbtype = "SQLite";
                dbtype = "SDF";
                m_Data.GetData(dbtype);
            }
    
        }
        private void btnZipFolder_Click(object sender, RoutedEventArgs e)
        {
            if (LiveClient == null)
                return;
            if (m_Data.LiveClient == null)
                m_Data.LiveClient = LiveClient;
            //m_Data.ZipFolder();
            m_Data.UpdateSkydriveFileList("C:\\IntexReport\\MINTEX");
        }
        
        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            if (m_Data.LiveClient == null)
                m_Data.LiveClient = LiveClient;
            m_Data.UploadZip();
        }
        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            SkyDriveLogIn();
            return;
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID = m_Data.Left(txtUserID.Text.ToUpper() + "        ", 8);
            System.Security.SecureString SPassword = txtPassword.SecurePassword;
            txtLogIn.Background = new SolidColorBrush(Colors.Yellow);
            DataSet setResult = m_Data.LogIn(Mandant, userID, SPassword);
            if (setResult.Tables.Count > 0)
            {
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                UserID = userID;
                m_Data.UserID = userID;
                this.UserID = userID;

                m_Data.WorkingDate = DateTime.Now.Year.ToString() + m_Data.Right("00" + DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + DateTime.Now.Day.ToString(), 2);
                m_Data.MANDANT = Mandant;
                m_Data.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "已登录";
                txtLogIn.Background = new SolidColorBrush(Colors.Green);

            }
        }
        #region=============SkyDrive=============
        Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
        {
            // Note: 
            // 1) In order to receive refresh token, wl.offline_access scope is needed.
            // 2) Alternatively, we can persist the refresh token.
            return Task.Factory.StartNew(() =>
            {
                this.refreshTokenInfo = tokenInfo;
            });
        }

        Task<RefreshTokenInfo> IRefreshTokenHandler.RetrieveRefreshTokenAsync()
        {
            return Task.Factory.StartNew<RefreshTokenInfo>(() =>
            {
                return this.refreshTokenInfo;
            });
        }
        #endregion 

    }
}